package com.h2.ref.server.auth.token;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

public class RandomTokenDaoInMem {
   
   private Map<String, Long> _tokens;
   
   ////
   ////
   
   public void init() {
      setTokens(new ConcurrentHashMap<String, Long>());
   }
   
   public String generateToken(int size, Integer minutesToExpire) {
      String token = AuthTokenUtils.mixedCaseAlphaNumericToken(size);
      storeToken(token, minutesToExpire);
      return token; 
   }
   
   public Boolean isTokenValid(String token) {
      Long time = getTokens().get(token);
      if (time == null) {
         return false;
      }
      else if (System.currentTimeMillis() - time <= 0) {
         deleteToken(token);
         return true;
      }
      else {
         return false;
      }
   }
   
   private void storeToken(String token, Integer minutesToExpire) {
      getTokens().put(token,
            System.currentTimeMillis() + minutesToExpire * 3600);
   }
   
   public void cleanTokens() {
      Iterator<Entry<String, Long>> entries = getTokens().entrySet().iterator();
      long time = System.currentTimeMillis();
      while(entries.hasNext()) {
         Entry<String, Long> entry = entries.next();
         if (time - entry.getValue() <= 0) {
            entries.remove();
         }
      }
   }
   
   public void deleteToken(String token) {
      getTokens().remove(token);
   }

   /**
    * @return the tokens
    */
   public Map<String, Long> getTokens() {
      return _tokens;
   }

   /**
    * @param tokens the tokens to set
    */
   public void setTokens(Map<String, Long> tokens) {
      _tokens = tokens;
   }

}
